package org.chibandroid.study;

import java.util.List;

import org.chibandroid.constant.TreasureConstant;
import org.chibandroid.database.DatabaseHelper;
import org.chibandroid.objectvalue.TreasureHuntValue;
import org.chibandroid.objectvalue.TreasureValues;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Paint.Cap;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.EditText;

public class TreasureSet extends MapActivity{

    /** Called when the activity is first created. */

   // ログ出力用のタグ
   private static final String TAG = "TragerHunt";
   // 地図の初期値（流山生涯学習センター）
   private static final int INITIAL_ZOOM_LEVE = 18;

   private int LATITUDE = TreasureConstant.LATITUDE;;
   private int LONGITUDE = TreasureConstant.LONGITUDE;

   private MapView mapView;
   private EditText mQuest1;
   private EditText mQuest2;
   private EditText mQuest3;
   private MapController controller;
   private List<Overlay> overlays;

   private TreasureHuntValue _value;
   private DatabaseHelper helper;
   private SQLiteDatabase db;
   private SQLiteStatement stmt;
   private Cursor cur;
   private int TreasreSeq;


	@Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.treasureset);

        mapView = (MapView) findViewById(R.id.mapview);
        mQuest1 = (EditText)findViewById(R.id.Quest1);
        mQuest2 = (EditText)findViewById(R.id.Quest2);
        mQuest3 = (EditText)findViewById(R.id.Quest3);

        _value = new TreasureHuntValue();
        getIntentData();

        mapView.setBuiltInZoomControls(true);
        mapView.displayZoomControls(true);

        // 位置とズームレベルの初期状態を設定する
        controller = mapView.getController();
        GeoPoint point = new GeoPoint(LATITUDE, LONGITUDE);
        controller.setCenter(point);
        controller.setZoom(INITIAL_ZOOM_LEVE);

        overlays = mapView.getOverlays();
        // イメージを地図上に表示する
        setOverlay(point);

    }

	@Override
	protected void onDestroy() {
		super.onDestroy();
		db.close();
		helper.close();
	}

	private void getIntentData(){

		Bundle extras = getIntent().getExtras();
		String _where = "TREASURENAME = ";
		if(extras != null){
			TreasureValues _values = (TreasureValues)extras.get(TreasureConstant.TREASUREMENU);
			if(_values != null){
		        setTitle(getTitle()+":"+_values.getTreasureName());
		        _value.setTreasureName(_values.getTreasureName());
		        _where += "'" + _values.getTreasureName() + "'";
			}

		}
    	helper = new DatabaseHelper(this);
    	db = helper.getReadableDatabase();
		cur = db.query("TREASUREHUNT", new String[]{"TREASURENAME"}, _where, null, null, null, null);
		TreasreSeq = cur.getCount();
		cur.close();
	}

	@Override
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        MenuItem item = menu.add(0, 0, 0, "登録").setIcon(android.R.drawable.ic_menu_edit);
        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
            	_value.setHint1(mQuest1.getText().toString());
            	_value.setHint2(mQuest2.getText().toString());
            	_value.setHint3(mQuest3.getText().toString());
            	_value.setLATITUDE(LATITUDE);
            	_value.setLONGITUDE(LONGITUDE);
            	TreasreSeq += 1;
            	setTreasureHunt();
                return true;
            }
        });
        return true;
    }

    private void setTreasureHunt(){

		String _sql = "INSERT INTO TREASUREHUNT VALUES (?, ?, ?, ?, ?, ?, ?);";
		db.beginTransaction();
		try{
			stmt = db.compileStatement(_sql);
			stmt.bindString(1,_value.getTreasureName());
			stmt.bindString(2,String.valueOf(TreasreSeq));
			stmt.bindString(3,_value.getHint1());
			stmt.bindString(4,_value.getHint2());
			stmt.bindString(5,_value.getHint3());
			stmt.bindString(6,String.valueOf(_value.getLATITUDE()));
			stmt.bindString(7,String.valueOf(_value.getLONGITUDE()));
			stmt.executeInsert();
			db.setTransactionSuccessful();
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			db.endTransaction();
			stmt.close();
		}
    }

	private IconOverlay overlay;
	private Bitmap icon = null;

	private void setOverlay(GeoPoint point) {

	       // Overlayクラスを生成する
		   if(icon!=null){
			   icon.recycle();
		   }

			Matrix matrix = new Matrix();
			matrix.postScale(0.5f, 0.5f);

	       Bitmap wicon = BitmapFactory.decodeResource(getResources(),R.drawable.point);
	       icon = Bitmap.createBitmap(wicon, 0, 0, wicon.getWidth(), wicon.getHeight(),matrix,true);
	       overlay = new IconOverlay(icon, point);
	       overlays.add(overlay);

	}

	   // 地図上に表示されるオーバーレイ
	private class IconOverlay extends Overlay{

	       // 描画するアイコン
       private Bitmap mIcon;
       private int mOffsetX;
       private int mOffsetY;
       private String sLocation;

       // アイコンを表示する位置
       private GeoPoint mPoint;

       public IconOverlay(Bitmap icon, GeoPoint initial) {
           // アイコンと、アイコンの中心のオフセット
			mIcon = icon;
			mOffsetX = 0 - icon.getWidth() / 2;
			mOffsetY = 0 - icon.getHeight();
			mPoint = initial;
			sLocation = "";

       }

       // 地図のタップ時に呼び出される
       @Override
       public boolean onTap(GeoPoint point, MapView mapView) {

	       // Overlayクラスを生成する
	       //icon = BitmapFactory.decodeResource(getResources(),R.drawable.point);
	       IconOverlay overlay = new IconOverlay(icon, point);
	       overlays.clear();
	       overlays.add(overlay);

           mPoint = point;
           MoveTo(mPoint);

           controller.animateTo(mPoint);

           return true;
       }



       public void MoveTo(GeoPoint point){

           mPoint = point;

           sLocation += "経度:" + String.valueOf(point.getLatitudeE6()) + '\n';
           sLocation += "緯度:" + String.valueOf(point.getLongitudeE6()) + '\n';

           LATITUDE = point.getLatitudeE6();
           LONGITUDE = point.getLongitudeE6();
           //Toast.makeText(getBaseContext(), sLocation, sLocation.length()).show();
           Log.d(TAG, sLocation);


       }

       // 地図の描画時に、shadow=true, shadow=falseと2回呼び出される
       @Override
       public void draw(Canvas canvas, MapView mapView,boolean shadow) {

           super.draw(canvas, mapView, shadow);
           // 地図上の場所と、描画用のCanvasの座標の変換
           Projection projection = mapView.getProjection();
           Point point = new Point();
           projection.toPixels(mPoint, point);
           point.offset(mOffsetX, mOffsetY);

           // アイコンを描画
           if (!shadow) {
               canvas.drawBitmap(mIcon, point.x, point.y, new Paint());
           }else{
        	   Paint paint = new Paint();
        	   paint.setAntiAlias(true);
        	   paint.setColor(Color.GRAY);
        	   paint.setStrokeCap(Cap.ROUND);
        	   paint.setStrokeWidth(5);
        	   canvas.drawCircle(point.x+(mIcon.getWidth()/2), point.y+mIcon.getHeight(), 10, paint);
           }
       }

   }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

}